package cn.utils;

import java.util.ArrayList;
import java.util.List;


/**
 * 辅助生成HQL的工具类
 * Created by Administrator on 2017/4/27.
 */
public class HQLHelper {
    private String formStr; //FROM子句
    private String whereStr="";    //where子句
    private String orderByStr="";  //ORDER BY子句
    private List<Object> args=new ArrayList<Object>();

    public List<Object> getArgs() {
        return args;
    }

    public void setArgs(List<Object> args) {
        this.args = args;
    }

    public HQLHelper(){

    }

    /**
     * 通过构造方法拼接FROM子句
     * @param clazz
     */
    public HQLHelper(Class clazz) {
        this.formStr=" FROM "+clazz.getSimpleName();
    }

    public void addWhere(String condition,Object...args){
        if(this.whereStr.length()==0){
            //第一次拼接where子句
            this.whereStr=" Where "+condition;
        }else{
            //不是第一次拼接
            this.whereStr+=" and "+condition;
        }
        if(args!=null&&args.length>0){
            //封装参数
            for(Object o:args){
                this.args.add(o);
            }
        }
    }

    /**
     * 拼接orDer By子句
     * @param orDerBy
     * @param asc
     */
    public void orDerBy(String orDerBy,boolean asc){
        if(this.orderByStr.length()==0){
            this.orderByStr=" Order By "+orDerBy+(asc?" asc":" desc");
        }
        else {
            this.orderByStr+=","+orDerBy+(asc?" asc":" desc");
        }
    }

    /**
     * 获取查询List集合的Hql语句
     * @return
     */
    public String getHqlList(){
        return this.formStr+this.whereStr+this.orderByStr;
    }
    public String getCountHql(){
        return "select count(*) "+this.formStr+" "+this.whereStr;
    }
}
